package com.chen.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.entity.Employee;
import com.chen.entity.R;
import com.chen.exception.NameDuplicateException;
import com.chen.mapper.EmployeeMapper;
import com.chen.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public R login(Employee employee) {
        //①.根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeMapper.selectOne(lqw);
        //②.如果没有查询到, 则返回登录失败结果
        if (emp == null) {
            return R.error("用户名不存在");
        }
        //③. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //④. 密码比对，如果不一致, 则返回登录失败结果
        if (!password.equals(emp.getPassword())) {
            return R.error("用户名密码错误");
        }
        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error(employee.getUsername() + "已被禁用,请联管理员");
        }
        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        return R.success(emp);
    }

    @Override
    public IPage<Employee> page(int page, int pageSize, String name) {
        IPage<Employee> ipage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        if (name != null && !name.equals("")) {
            lqw.like(Employee::getName, name);
        }
        return employeeMapper.selectPage(ipage, lqw);

    }

    @Override
    public void add(Employee employee) {

        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        log.info(employee.toString());
        try {
            employeeMapper.insert(employee);
        } catch (Exception e) {
            throw new NameDuplicateException();
        }
    }

    @Override
    public Employee findByid(Long id) {
        return getById(id);
        //return employeeMapper.selectById(id);
    }
}
